// pages/admin/activity/edit/edit.js
const activityApi = require('../../../../api/activity.js')
const activityItemApi = require('../../../../api/activity_item.js')
const util = require('../../../../utils/util.js')
const api = require('../../../../utils/api.js')

Page({
  data: {
    activityId: null,
    isEdit: false,
    formData: {
      title: '',
      description: '',
      rules: '',
      // 模板类型
      template_type: 'chinese',  // chinese 或 english
      // 联系我
      contact_name: '',
      // 地址信息
      address: '',
      latitude: 0,
      longitude: 0,
      // 会议时间
      start_date: '',
      start_time: '19:00',
      end_date: '',
      end_time: '21:00',
      // 报名时间
      registration_start_date: '',
      registration_start_time: '00:00',
      registration_end_date: '',
      registration_end_time: '23:59',
      // 加油信息
      voting_enabled: false,
      voting_start_date: '',
      voting_start_time: '00:00',
      voting_end_date: '',
      voting_end_time: '23:59',
      max_votes_per_user: 1
    },
    submitting: false,
    // 报名弹窗相关
    showRegisterModal: false,
    currentItem: {},
    registerForm: {
      name: '',
      introduction: '',
      photo_url: '',
      speech_intro: ''
    },
    // 项目管理相关
    activityItems: [],
    roleCategories: [],  // 角色分类列表
    showItemModal: false,
    editingItem: {
      name: '',
      description: '',
      role_category_id: null,
      role_category_name: '',
      roleCategoryIndex: 0,
      max_registrations: 0,
      require_introduction: true,
      require_photo: true,
      require_speech_intro: true
    },
    itemSubmitting: false
  },

  onLoad(options) {
    if (options.id) {
      this.setData({ 
        activityId: options.id,
        isEdit: true
      })
      this.loadActivityDetail()
      this.loadActivityItems()
    }
    // 加载角色分类
    this.loadRoleCategories()
  },

  async loadActivityDetail() {
    try {
      const res = await activityApi.getActivityDetail(this.data.activityId)
      
      if (res.code === 200) {
        const activity = res.data
        
        // 解析日期时间
        const parseDateTime = (datetime) => {
          if (!datetime) return { date: '', time: '' }
          const parts = datetime.split(' ')
          return {
            date: parts[0] || '',
            time: parts[1] ? parts[1].substring(0, 5) : ''
          }
        }
        
        const startDT = parseDateTime(activity.start_time)
        const endDT = parseDateTime(activity.end_time)
        const regStartDT = parseDateTime(activity.registration_start_time)
        const regEndDT = parseDateTime(activity.registration_end_time)
        const voteStartDT = parseDateTime(activity.voting_start_time)
        const voteEndDT = parseDateTime(activity.voting_end_time)
        
        this.setData({
          formData: {
            title: activity.title,
            description: activity.description,
            rules: activity.rules || '',
            contact_name: activity.contact_name || '',
            contact_wechat: activity.contact_wechat || '',
            contact_phone: activity.contact_phone || '',
            address: activity.address || '',
            latitude: activity.latitude || 0,
            longitude: activity.longitude || 0,
            start_date: startDT.date,
            start_time: startDT.time || '19:00',
            end_date: endDT.date,
            end_time: endDT.time || '21:00',
            registration_start_date: regStartDT.date,
            registration_start_time: regStartDT.time || '00:00',
            registration_end_date: regEndDT.date,
            registration_end_time: regEndDT.time || '23:59',
            voting_enabled: activity.voting_enabled,
            voting_start_date: voteStartDT.date,
            voting_start_time: voteStartDT.time || '00:00',
            voting_end_date: voteEndDT.date,
            voting_end_time: voteEndDT.time || '23:59',
            max_votes_per_user: activity.max_votes_per_user || 1
          }
        })
      }
    } catch (error) {
      console.error('加载会议详情失败:', error)
      util.showError('加载失败')
    }
  },

  onInputChange(e) {
    const field = e.currentTarget.dataset.field
    this.setData({
      [`formData.${field}`]: e.detail.value
    })
  },

  // 模板类型切换
  onTemplateChange(e) {
    const type = e.currentTarget.dataset.type
    this.setData({
      'formData.template_type': type
    })
  },

  onDateChange(e) {
    const field = e.currentTarget.dataset.field
    this.setData({
      [`formData.${field}`]: e.detail.value
    })
  },

  onTimeChange(e) {
    const field = e.currentTarget.dataset.field
    this.setData({
      [`formData.${field}`]: e.detail.value
    })
  },

  onVotingChange(e) {
    const currentValue = this.data.formData.voting_enabled
    const newValue = !currentValue
    this.setData({
      'formData.voting_enabled': newValue
    })
    console.log(`✅ 加油功能切换: ${currentValue} → ${newValue}`)
  },

  // 选择地址
  chooseLocation() {
    wx.chooseLocation({
      success: (res) => {
        console.log('选择的位置:', res)
        this.setData({
          'formData.address': res.address + res.name,
          'formData.latitude': res.latitude,
          'formData.longitude': res.longitude
        })
      },
      fail: (err) => {
        console.log('选择位置失败:', err)
        // 用户拒绝隐私授权（错误码 103 或 104）
        if (err.errMsg.includes('104') || err.errMsg.includes('privacy')) {
          wx.showModal({
            title: '需要授权',
            content: '为了选择会议地点，需要您同意隐私保护指引。',
            showCancel: true,
            confirmText: '我知道了'
          })
        } else if (err.errMsg.includes('auth deny')) {
          util.showError('请授权位置权限')
        } else if (!err.errMsg.includes('cancel')) {
          util.showError('选择位置失败')
        }
      }
    })
  },

  validateForm() {
    const { 
      title, description, 
      start_date, start_time, end_date, end_time,
      registration_start_date, registration_start_time, 
      registration_end_date, registration_end_time,
      voting_enabled, voting_start_date, voting_start_time,
      voting_end_date, voting_end_time, max_votes_per_user 
    } = this.data.formData

    if (!title.trim()) {
      util.showError('请输入会议标题')
      return false
    }

    if (!description.trim()) {
      util.showError('请输入会议描述')
      return false
    }

    if (!start_date || !end_date) {
      util.showError('请选择会议时间')
      return false
    }

    // 验证会议时间
    const startDateTime = new Date(`${start_date} ${start_time}:00`)
    const endDateTime = new Date(`${end_date} ${end_time}:00`)
    
    if (endDateTime <= startDateTime) {
      util.showError('会议结束时间必须晚于开始时间')
      return false
    }

    if (!registration_start_date || !registration_end_date) {
      util.showError('请选择报名时间')
      return false
    }

    // 验证报名时间
    const regStartDateTime = new Date(`${registration_start_date} ${registration_start_time}:00`)
    const regEndDateTime = new Date(`${registration_end_date} ${registration_end_time}:00`)
    
    if (regEndDateTime <= regStartDateTime) {
      util.showError('报名结束时间必须晚于开始时间')
      return false
    }

    if (voting_enabled) {
      if (!voting_start_date || !voting_end_date) {
        util.showError('请选择加油时间')
        return false
      }

      // 验证加油时间
      const voteStartDateTime = new Date(`${voting_start_date} ${voting_start_time}:00`)
      const voteEndDateTime = new Date(`${voting_end_date} ${voting_end_time}:00`)
      
      if (voteEndDateTime <= voteStartDateTime) {
        util.showError('加油结束时间必须晚于开始时间')
        return false
      }

      if (!max_votes_per_user || max_votes_per_user < 1) {
        util.showError('每人限加油数必须大于0')
        return false
      }
    }

    return true
  },

  async submitForm() {
    if (!this.validateForm()) return

    if (this.data.submitting) return

    this.setData({ submitting: true })

    try {
      const fd = this.data.formData
      
      const data = {
        title: fd.title,
        description: fd.description,
        rules: fd.rules,
        template_type: fd.template_type || 'chinese',  // 添加模板类型
        contact_name: fd.contact_name,
        contact_wechat: fd.contact_wechat,
        contact_phone: fd.contact_phone,
        address: fd.address,
        latitude: fd.latitude,
        longitude: fd.longitude,
        start_time: `${fd.start_date} ${fd.start_time}:00`,
        end_time: `${fd.end_date} ${fd.end_time}:00`,
        registration_start_time: `${fd.registration_start_date} ${fd.registration_start_time}:00`,
        registration_end_time: `${fd.registration_end_date} ${fd.registration_end_time}:00`,
        voting_enabled: fd.voting_enabled
      }
      
      if (fd.voting_enabled) {
        data.voting_start_time = `${fd.voting_start_date} ${fd.voting_start_time}:00`
        data.voting_end_time = `${fd.voting_end_date} ${fd.voting_end_time}:00`
        data.max_votes_per_user = parseInt(fd.max_votes_per_user)
      }

      let res
      if (this.data.isEdit) {
        res = await activityApi.updateActivity(this.data.activityId, data)
      } else {
        res = await activityApi.createActivity(data)
      }

      if (res.code === 200 || res.success) {
        util.showSuccess(this.data.isEdit ? '更新成功' : '创建成功')
        
        // 如果是创建，提示会议已创建为草稿状态
        if (!this.data.isEdit) {
          setTimeout(() => {
            wx.showModal({
              title: '提示',
              content: '会议已创建为草稿状态，您可以在会议管理中继续编辑或发布',
              showCancel: false,
              success: () => {
                wx.navigateBack()
              }
            })
          }, 500)
        } else {
          setTimeout(() => {
            wx.navigateBack()
          }, 1500)
        }
      } else {
        util.showError(res.message || '操作失败')
      }
    } catch (error) {
      console.error('提交失败:', error)
      util.showError('操作失败，请重试')
    } finally {
      this.setData({ submitting: false })
    }
  },

  // ========== 报名弹窗相关 ==========

  openRegisterModal(e) {
    const item = e.currentTarget.dataset.item
    this.setData({
      showRegisterModal: true,
      currentItem: item,
      registerForm: {
        name: '',
        introduction: '',
        photo_url: '',
        speech_intro: ''
      }
    })
  },

  closeRegisterModal() {
    this.setData({
      showRegisterModal: false,
      currentItem: {},
      registerForm: {
        name: '',
        introduction: '',
        photo_url: '',
        speech_intro: ''
      }
    })
  },

  preventClose() {
    // 阻止冒泡，防止点击内容区域关闭弹窗
  },

  onRegisterInput(e) {
    const field = e.currentTarget.dataset.field
    this.setData({
      [`registerForm.${field}`]: e.detail.value
    })
  },

  // 选择/拍摄照片
  choosePhoto() {
    wx.showActionSheet({
      itemList: ['拍照', '从相册选择'],
      success: (res) => {
        const sourceType = res.tapIndex === 0 ? ['camera'] : ['album']
        
        wx.chooseImage({
          count: 1,
          sizeType: ['compressed'],
          sourceType: sourceType,
          success: (res) => {
            const tempFilePath = res.tempFilePaths[0]
            
            // 这里简化处理，直接使用本地路径
            // 在实际使用中，应该上传到服务器获取URL
            this.setData({
              'registerForm.photo_url': tempFilePath
            })
            
            util.showSuccess('照片已选择')
          },
          fail: (err) => {
            console.log('选择照片失败:', err)
            // 用户拒绝隐私授权
            if (err.errMsg && (err.errMsg.includes('104') || err.errMsg.includes('privacy'))) {
              wx.showModal({
                title: '需要授权',
                content: '为了上传照片，需要您同意隐私保护指引。',
                showCancel: false,
                confirmText: '我知道了'
              })
            } else if (!err.errMsg || !err.errMsg.includes('cancel')) {
              util.showError('选择照片失败')
            }
          }
        })
      }
    })
  },

  // 提交报名
  async submitRegister() {
    const { name, introduction, photo_url, speech_intro } = this.data.registerForm

    if (!name.trim()) {
      util.showError('请输入"我是谁"')
      return
    }

    if (!introduction.trim()) {
      util.showError('请输入自我介绍')
      return
    }

    if (!photo_url) {
      util.showError('请上传个人照片')
      return
    }

    if (!speech_intro.trim()) {
      util.showError('请输入演讲介绍')
      return
    }

    try {
      wx.showLoading({ title: '提交中...' })
      
      // TODO: 这里应该先上传照片到服务器，获取真实的URL
      // 现在暂时使用本地路径（实际部署时需要实现文件上传）
      
      const res = await activityItemApi.registerForItem(
        this.data.activityId,
        this.data.currentItem.id,
        this.data.registerForm
      )

      wx.hideLoading()

      if (res.code === 200 || res.success) {
        util.showSuccess('报名成功')
        this.closeRegisterModal()
        // 重新加载项目列表（如果在详情页）
        // this.loadActivityItems()
      } else {
        util.showError(res.message || '报名失败')
      }
    } catch (error) {
      wx.hideLoading()
      console.error('报名失败:', error)
      util.showError('报名失败，请重试')
    }
  },

  // ========== 项目管理相关方法 ==========

  /**
   * 加载活动的所有报名项目
   */
  async loadActivityItems() {
    try {
      const res = await activityItemApi.getActivityItems(this.data.activityId)
      
      if (res.code === 200 || res.success) {
        const items = res.data.items || []
        this.setData({ activityItems: items })
        console.log('✅ 加载项目列表成功:', items.length)
      }
    } catch (error) {
      console.error('❌ 加载项目列表失败:', error)
    }
  },

  /**
   * 加载角色分类列表
   */
  async loadRoleCategories() {
    try {
      const res = await api.request('/role-categories', 'GET')
      
      console.log('🔍 API返回数据:', res)
      console.log('🔍 res.data类型:', typeof res.data, '内容:', res.data)
      
      if (res.code === 200 || res.success) {
        const categories = res.data || []
        console.log('🔍 分类数组:', categories)
        console.log('🔍 分类数量:', categories.length)
        
        this.setData({ roleCategories: categories }, () => {
          console.log('✅ roleCategories已设置:', this.data.roleCategories)
        })
      } else {
        console.error('❌ API返回失败:', res)
      }
    } catch (error) {
      console.error('❌ 加载角色分类失败:', error)
    }
  },

  /**
   * 角色分类选择变化
   */
  onRoleCategoryChange(e) {
    const index = e.detail.value
    const category = this.data.roleCategories[index]
    
    this.setData({
      'editingItem.role_category_id': category.id,
      'editingItem.role_category_name': category.name,
      'editingItem.roleCategoryIndex': index
    })
    
    console.log('✅ 选择角色分类:', category.name)
  },

  /**
   * 显示添加项目弹窗
   */
  showAddItemModal() {
    this.setData({
      showItemModal: true,
      editingItem: {
        name: '',
        description: ''
      }
    })
  },

  /**
   * 显示项目操作菜单
   */
  showItemActions(e) {
    const item = e.currentTarget.dataset.item
    const hasRegistrations = (item.registration_count || 0) > 0
    
    // 构建操作选项列表
    const itemList = [
      '✏️ 修改',
      '➕ 往前插入一行',
      '➕ 往后插入一行',
      hasRegistrations ? '🗑️ 删除（已有人报名，不可删除）' : '🗑️ 删除',
      '🚫 禁用'
    ]
    
    wx.showActionSheet({
      itemList: itemList,
      success: (res) => {
        const tapIndex = res.tapIndex
        
        if (tapIndex === 0) {
          // 修改
          this.showEditItemModal(item)
        } else if (tapIndex === 1) {
          // 往前插入一行
          this.insertItemBefore(item)
        } else if (tapIndex === 2) {
          // 往后插入一行
          this.insertItemAfter(item)
        } else if (tapIndex === 3) {
          // 删除
          if (!hasRegistrations) {
            this.confirmDeleteItem(item)
          } else {
            util.showError('该项目已有人报名，不能删除')
          }
        } else if (tapIndex === 4) {
          // 禁用
          this.toggleItemStatus(item)
        }
      },
      fail: (err) => {
        console.log('用户取消操作')
      }
    })
  },

  /**
   * 显示编辑项目弹窗
   */
  showEditItemModal(item) {
    // 查找角色分类索引
    let roleCategoryIndex = 0
    if (item.role_category_id && this.data.roleCategories.length > 0) {
      roleCategoryIndex = this.data.roleCategories.findIndex(cat => cat.id === item.role_category_id)
      if (roleCategoryIndex === -1) roleCategoryIndex = 0
    }
    
    this.setData({
      showItemModal: true,
      editingItem: {
        id: item.id,
        name: item.name,
        description: item.description || '',
        role_category_id: item.role_category_id,
        role_category_name: item.role_category_name || '',
        roleCategoryIndex: roleCategoryIndex,
        max_registrations: item.max_registrations || 0,
        require_introduction: item.require_introduction !== false,
        require_photo: item.require_photo !== false,
        require_speech_intro: item.require_speech_intro !== false
      }
    })
    console.log('📝 编辑项目:', this.data.editingItem)
  },

  /**
   * 关闭项目弹窗
   */
  closeItemModal() {
    this.setData({
      showItemModal: false,
      editingItem: {}
    })
  },

  /**
   * 项目表单输入
   */
  onItemInput(e) {
    const field = e.currentTarget.dataset.field
    this.setData({
      [`editingItem.${field}`]: e.detail.value
    })
  },

  /**
   * 切换复选框状态
   */
  toggleCheckbox(e) {
    const field = e.currentTarget.dataset.field
    const currentValue = this.data.editingItem[field]
    const newValue = !currentValue
    
    this.setData({
      [`editingItem.${field}`]: newValue
    })
    console.log(`✅ 复选框切换: ${field} = ${currentValue} → ${newValue}`)
  },

  /**
   * 提交项目（创建或更新）
   */
  async submitItem() {
    const { name, insertPosition, referenceSequence } = this.data.editingItem
    
    if (!name.trim()) {
      util.showError('请输入项目名称')
      return
    }

    if (this.data.itemSubmitting) return
    
    this.setData({ itemSubmitting: true })

    try {
      wx.showLoading({ title: '提交中...' })

      let res
      if (this.data.editingItem.id) {
        // 更新项目
        const updateData = {
          name: this.data.editingItem.name,
          description: this.data.editingItem.description,
          role_category_id: this.data.editingItem.role_category_id,
          max_registrations: parseInt(this.data.editingItem.max_registrations) || 0,
          require_introduction: this.data.editingItem.require_introduction !== false,
          require_photo: this.data.editingItem.require_photo !== false,
          require_speech_intro: this.data.editingItem.require_speech_intro !== false
        }
        
        console.log('📤 提交更新数据:', updateData)
        
        res = await activityItemApi.updateItem(
          this.data.activityId,
          this.data.editingItem.id,
          updateData
        )
      } else {
        // 创建新项目
        const itemData = {
          name: this.data.editingItem.name,
          description: this.data.editingItem.description,
          role_category_id: this.data.editingItem.role_category_id || this.data.roleCategories[0]?.id,
          max_registrations: parseInt(this.data.editingItem.max_registrations) || 0,
          require_introduction: this.data.editingItem.require_introduction !== false,
          require_photo: this.data.editingItem.require_photo !== false,
          require_speech_intro: this.data.editingItem.require_speech_intro !== false
        }
        
        // 如果是插入操作，计算sequence
        if (insertPosition && referenceSequence) {
          if (insertPosition === 'before') {
            // 往前插入：新sequence = 参考sequence - 0.5
            itemData.sequence = referenceSequence - 0.5
          } else if (insertPosition === 'after') {
            // 往后插入：新sequence = 参考sequence + 0.5
            itemData.sequence = referenceSequence + 0.5
          }
        }
        
        res = await activityItemApi.createItem(
          this.data.activityId,
          itemData
        )
      }

      wx.hideLoading()

      if (res.code === 200 || res.success) {
        util.showSuccess(this.data.editingItem.id ? '更新成功' : '创建成功')
        this.closeItemModal()
        this.loadActivityItems()
      } else {
        util.showError(res.message || '操作失败')
      }
    } catch (error) {
      wx.hideLoading()
      console.error('提交项目失败:', error)
      util.showError('操作失败，请重试')
    } finally {
      this.setData({ itemSubmitting: false })
    }
  },

  /**
   * 确认删除项目
   */
  confirmDeleteItem(item) {
    wx.showModal({
      title: '确认删除',
      content: `确定要删除项目"${item.name}"吗？\n\n注意：如果该项目已有人报名，则无法删除。`,
      confirmText: '删除',
      confirmColor: '#ff4d4f',
      success: (res) => {
        if (res.confirm) {
          this.deleteItem(item.id)
        }
      }
    })
  },

  /**
   * 在指定项目前插入一行
   */
  insertItemBefore(item) {
    wx.showModal({
      title: '提示',
      content: `确定要在"${item.name}"前插入一个新项目吗？`,
      success: (res) => {
        if (res.confirm) {
          this.setData({
            showItemModal: true,
            editingItem: {
              name: '',
              description: '',
              insertPosition: 'before',
              referenceSequence: item.sequence
            }
          })
        }
      }
    })
  },

  /**
   * 在指定项目后插入一行
   */
  insertItemAfter(item) {
    wx.showModal({
      title: '提示',
      content: `确定要在"${item.name}"后插入一个新项目吗？`,
      success: (res) => {
        if (res.confirm) {
          this.setData({
            showItemModal: true,
            editingItem: {
              name: '',
              description: '',
              insertPosition: 'after',
              referenceSequence: item.sequence
            }
          })
        }
      }
    })
  },

  /**
   * 切换项目启用/禁用状态
   */
  toggleItemStatus(item) {
    // TODO: 后端需要添加状态字段和更新接口
    util.showToast('禁用功能开发中，敬请期待', 'none')
    
    // 未来实现示例：
    // wx.showModal({
    //   title: '提示',
    //   content: `确定要${item.is_enabled ? '禁用' : '启用'}"${item.name}"吗？`,
    //   success: async (res) => {
    //     if (res.confirm) {
    //       try {
    //         await activityItemApi.updateItem(this.data.activityId, item.id, {
    //           is_enabled: !item.is_enabled
    //         })
    //         util.showSuccess(item.is_enabled ? '已禁用' : '已启用')
    //         this.loadActivityItems()
    //       } catch (error) {
    //         util.showError('操作失败')
    //       }
    //     }
    //   }
    // })
  },

  /**
   * 删除项目
   */
  async deleteItem(itemId) {
    try {
      wx.showLoading({ title: '删除中...' })

      const res = await activityItemApi.deleteItem(this.data.activityId, itemId)

      wx.hideLoading()

      if (res.code === 200 || res.success) {
        util.showSuccess('删除成功')
        this.loadActivityItems()
      } else {
        util.showError(res.message || '删除失败')
      }
    } catch (error) {
      wx.hideLoading()
      console.error('删除项目失败:', error)
      util.showError('删除失败，请重试')
    }
  },

  /**
   * 阻止事件冒泡
   */
  preventClose() {
    // 阻止弹窗内部点击事件冒泡
  }
})
